#!/usr/bin/env tsx

/**
 * 数据库配置文件系统演示脚本
 * 
 * 运行方式：npx tsx scripts/demo-database-config.ts
 */

import { dataSourceFactory } from '../src/orm/adapters/datasource';
import { databaseConfigLoader } from '../packages/shared-types/src/config/database-config-loader';

async function demonstrateConfigSystem() {
  console.log('🚀 数据库配置文件系统演示\n');
  
  try {
    // 1. 显示配置文件信息
    console.log('📋 配置文件信息:');
    const environments = databaseConfigLoader.getAvailableEnvironments();
    console.log(`   可用环境: ${environments.join(', ')}`);
    
    for (const env of environments) {
      const connections = databaseConfigLoader.getAvailableConnections(env);
      console.log(`   ${env} 环境连接: ${connections.join(', ')}`);
    }
    console.log();
    
    // 2. 验证配置文件
    console.log('✅ 验证配置文件...');
    databaseConfigLoader.validateConfig();
    console.log('   配置文件验证通过\n');
    
    // 3. 创建默认数据源（SQLite）
    console.log('🔗 创建默认数据源 (SQLite):');
    const defaultDataSource = await dataSourceFactory.createFromConfigFile();
    console.log(`   类型: ${defaultDataSource.options.type}`);
    console.log(`   数据库: ${defaultDataSource.options.database}`);
    console.log(`   已初始化: ${defaultDataSource.isInitialized}\n`);
    
    // 4. 获取数据源信息
    console.log('📊 当前数据源状态:');
    const dataSourceInfo = dataSourceFactory.getDataSourceInfo();
    dataSourceInfo.forEach(info => {
      console.log(`   ${info.name}: ${info.type} (${info.isInitialized ? '已连接' : '未连接'})`);
    });
    console.log();
    
    // 5. 测试连接
    console.log('🔍 测试数据库连接...');
    const defaultConfig = databaseConfigLoader.getConnectionConfig();
    const isConnected = await dataSourceFactory.testConnection({
      name: 'default',
      type: defaultConfig.type === 'mongodb' ? 'mysql' : defaultConfig.type,
      host: defaultConfig.host,
      port: defaultConfig.port,
      username: defaultConfig.username,
      password: defaultConfig.password,
      database: defaultConfig.database,
      synchronize: defaultConfig.synchronize,
      logging: defaultConfig.logging
    });
    console.log(`   连接测试: ${isConnected ? '✅ 成功' : '❌ 失败'}\n`);
    
    // 6. 显示具体配置
    console.log('⚙️  当前环境配置详情:');
    const currentEnv = process.env.NODE_ENV || 'development';
    const allConnections = databaseConfigLoader.getAllConnectionsForEnvironment(currentEnv);
    
    for (const [name, config] of Object.entries(allConnections)) {
      console.log(`   ${name}:`);
      console.log(`     类型: ${config.type}`);
      if (config.host) console.log(`     主机: ${config.host}:${config.port || 'default'}`);
      console.log(`     数据库: ${config.database}`);
      console.log(`     同步: ${config.synchronize ? '启用' : '禁用'}`);
      console.log(`     日志: ${config.logging ? '启用' : '禁用'}`);
      console.log();
    }
    
  } catch (error) {
    console.error('❌ 演示过程中发生错误:', error.message);
  } finally {
    // 7. 清理资源
    console.log('🧹 清理数据源连接...');
    await dataSourceFactory.closeAll();
    console.log('   所有连接已关闭');
  }
}

// 环境变量演示
function demonstrateEnvironmentVariables() {
  console.log('\n🌍 环境变量支持演示:');
  console.log('   在生产环境中，可以使用以下环境变量:');
  console.log('   export DB_HOST=your-db-host.com');
  console.log('   export DB_PORT=5432');
  console.log('   export DB_USERNAME=your-username');
  console.log('   export DB_PASSWORD=your-password');
  console.log('   export DB_DATABASE=your-database');
  console.log('   export NODE_ENV=production');
  console.log();
  
  // 模拟设置环境变量
  const originalEnv = { ...process.env };
  
  try {
    process.env.DB_HOST = 'demo-server.example.com';
    process.env.DB_PORT = '5432';
    process.env.DB_USERNAME = 'demo_user';
    process.env.DB_PASSWORD = 'demo_password';
    process.env.DB_DATABASE = 'demo_database';
    
    console.log('   设置演示环境变量后的生产配置:');
    databaseConfigLoader.reloadConfig();
    const prodConfig = databaseConfigLoader.getConnectionConfig('production', 'default');
    
    console.log(`     主机: ${prodConfig.host}`);
    console.log(`     端口: ${prodConfig.port}`);
    console.log(`     用户: ${prodConfig.username}`);
    console.log(`     数据库: ${prodConfig.database}`);
    console.log(`     密码: ${'*'.repeat(prodConfig.password?.length || 0)}`);
    
  } finally {
    // 恢复原始环境变量
    process.env = originalEnv;
    databaseConfigLoader.reloadConfig();
  }
}

// 主函数
async function main() {
  await demonstrateConfigSystem();
  demonstrateEnvironmentVariables();
  
  console.log('\n🎉 演示完成！');
  console.log('\n📚 更多信息请查看:');
  console.log('   - 配置文件: config/database.json');
  console.log('   - 文档: config/README.md');
  console.log('   - 使用示例: examples/database-config-usage.ts');
  console.log('   - 测试文件: src/config/__tests__/database-config-loader.test.ts');
}

// 检查是否为主模块运行
if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch(console.error);
}

export { demonstrateConfigSystem, demonstrateEnvironmentVariables };